import type { FormItem } from '@/components/FormDialog/data';
import ToeForm from '@/components/FormDialog/index';
import ToeUpload from '@/components/UploadDialog/index';
import {
  addLicense,
  customerCodeList,
  customerList,
  delLicense,
  delLicenses,
  genLicense,
  getLicenseByPage,
  licenseExcelExport,
  sendEmail,
  updateLicense,
  updateLicensesCustomer,
  updateLicensesUser,
  uploadLicenseExcel,
  userLicenseList,
} from '@/services/sales/license';
import { PlusOutlined } from '@ant-design/icons';
import {
  ModalForm,
  ProFormDatePicker,
  ProFormDependency,
  ProFormDigit,
  ProFormGroup,
  ProFormMoney,
  ProFormSelect,
  ProFormText,
} from '@ant-design/pro-components';
import { PageContainer } from '@ant-design/pro-layout';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import { Button, DatePicker, Form, InputNumber, message, Modal, Select, Tag } from 'antd';
import type { FormLayout } from 'antd/es/form/Form';

import { Spin } from 'antd';
import type { SelectProps } from 'antd/es/select';
import debounce from 'lodash/debounce';
import React, { useMemo, useRef, useState } from 'react';
import { useAccess, useLocation } from 'umi';
import dayjs from 'dayjs';
import placements from 'rc-tooltip/lib/placements';

const { Option } = Select;

export interface DebounceSelectProps<ValueType = any>
  extends Omit<SelectProps<ValueType | ValueType[]>, 'options' | 'children'> {
  fetchOptions: (search: string) => Promise<ValueType[]>;
  debounceTimeout?: number;
}

function DebounceSelect<
  ValueType extends { key?: string; label: React.ReactNode; value: string | number } = any,
>({ fetchOptions, debounceTimeout = 800, ...props }: DebounceSelectProps<ValueType>) {
  const [fetching, setFetching] = useState(false);
  const [options, setOptions] = useState<ValueType[]>([]);
  const fetchRef = useRef(0);

  const debounceFetcher = useMemo(() => {
    const loadOptions = (value: string) => {
      fetchRef.current += 1;
      const fetchId = fetchRef.current;
      setOptions([]);
      setFetching(true);

      fetchOptions(value).then((newOptions) => {
        if (fetchId !== fetchRef.current) {
          // for fetch callback order
          return;
        }

        setOptions(newOptions);
        setFetching(false);
      });
    };

    return debounce(loadOptions, debounceTimeout);
  }, [fetchOptions, debounceTimeout]);

  return (
    <Select
      // style={{
      //   width: '400',
      // }}
      labelInValue
      filterOption={false}
      onSearch={debounceFetcher}
      notFoundContent={fetching ? <Spin size="small" /> : null}
      {...props}
      options={options}
    />
  );
}

// Usage of DebounceSelect
interface UserValue {
  label: string;
  value: string;
}

async function fetchUserList(username: string): Promise<UserValue[]> {
  console.log('fetching user', username);
  return customerList({ blurry: username }).then((res) => {
    return res.data.map((item) => {
      return {
        label: item.name,
        value: item.id,
      };
    });
  });
}

async function fetchUserCodeList(username: string): Promise<UserValue[]> {
  console.log('fetching user', username);
  return customerCodeList({ blurry: username }).then((res) => {
    return res.data.map((item) => {
      return {
        // label: item.code,
        label: item.name,
        value: item.id,
      };
    });
  });

  // return fetch('https://randomuser.me/api/?results=5')
  //   .then((response) => response.json())
  //   .then((body) =>
  //     body.results.map(
  //       (user: { name: { first: string; last: string }; login: { username: string } }) => ({
  //         label: `${user.name.first} ${user.name.last}`,
  //         value: user.login.username,
  //       }),
  //     ),
  //   );
}
const LAYOUT_TYPE_HORIZONTAL = 'horizontal';
const LicenseAdm: React.FC<{}> = () => {
  const [uploadVisit, setUploadVisit] = useState(false); //上传按钮显示
  const [formTitle, setFormTitle] = useState('新建授权号'); //
  const ref = useRef(null);
  const [formUserTitle, setFormUserTitle] = useState('授权'); //
  const [formUserVisit, setFormUserVisit] = useState(false); //
  const actionRef = useRef<ActionType>();
  const [formVisit, setFormVisit] = useState(false); // form表单设置
  const [formDisabled, setFormDisabled] = useState(false); //设置表单禁用
  const [form] = Form.useForm();
  const uploadRef = useRef(null);
  const formRef = useRef(null);
  const [userData, setUserData] = useState<object[]>([{ id: '', name: '' }]);
  const [value, setValue] = useState<UserValue[]>([]);
  const [selectRows, setSelectRows] = useState([]);
  const [confirmLoading, setConfirmLoading] = useState(false); //编辑框的disable

  const [transNumMax, setTransNumMax] = useState(0);

  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const [formLayoutType, setFormLayoutType] = useState<FormLayout>(LAYOUT_TYPE_HORIZONTAL);
  const [grid, setGrid] = useState(true);

  const [genVisible, setGenVisible] = useState(false);
  const genFormRef = useRef<ProFormInstance>();
  // const [purchaseDate, setPurchaseDate] = useState('');

  const [mailVisible, setMailVisible] = useState(false);
  const mailFormRef = useRef<ProFormInstance>();
  const [customerId, setCustomerId] = useState('');
  const [customerName, setCustomerName] = useState('');
  const [emailinitialValues, setEmailinitialValues] = useState({});
  const access = useAccess();
  const onSelectChange = (newSelectedRowKeys: React.Key[], selectedRows) => {
    setSelectedRowKeys(newSelectedRowKeys);
  };
  const rowSelection = {
    selectedRowKeys,
    onChange: onSelectChange,
  };

  const location = useLocation();
  const licenseTypeMap = new Map([
    [1, 'BD推广'],
    [2, '基本版'],
    [3, '尊享版'],
    [4, '高级版'],
    [5, '10Package'],
    [6, '50Package'],
    [7, '堆垛机版'],

    [11, '会员版'],
    [12, '单台设备'],
    [13, '同类包年'],
    [14, '线下尊享版'],
  ]);

  const statusMap = new Map([
    [true, '使用'],
    [false, '未使用'],
  ]);

  const statusMapColor = new Map([
    [true, 'red'],
    [false, 'green'],
  ]);

  /**
   * 穿梭框的数据设置
   */
  const columns: ProColumns[] = [
    {
      title: '序号',
      dataIndex: 'index',
      valueType: 'index',
      width: 50,
    },
    {
      title: '唯一编号', //表头显示的名称
      search: false,
      dataIndex: 'identification', // 列数据在数据项中对应的路径，支持通过数组查询嵌套路径
      width: 150,
    },

    {
      title: '授权号类型', //表头显示的名称
      search: false,
      dataIndex: 'licenseType', // 列数据在数据项中对应的路径，支持通过数组查询嵌套路径
      width: 100,
      render: (_, record) => <Tag color={'green'}>{licenseTypeMap.get(record.licenseType)}</Tag>,
    },
    {
      title: '使用状态',
      dataIndex: 'status',
      // hideInTable: true,
      valueType: 'select',
      render: (_, record) => (
        <Tag color={statusMapColor.get(record.status)}>{statusMap.get(record.status)}</Tag>
      ),
      valueEnum: {
        true: '使用',
        false: '未使用',
      },
    },

    {
      title: '授权号类型',
      dataIndex: 'licenseType',
      hideInTable: true,
      valueType: 'select',
      valueEnum: {
        1: 'BD推广',
        2: '基本版',
        3: '尊享版',
        4: '高级版',
        5: '10Package',
        6: '50Package',
        7: '堆垛机版',

        11: '会员版',
        12: '单台设备',
        13: '同类包年',
        14: '线下尊享版',
      },
    },
    {
      title: '授权号', //表头显示的名称
      // search: false,
      dataIndex: 'licenseID', // 列数据在数据项中对应的路径，支持通过数组查询嵌套路径
      width: 180,
    },
    {
      title: '订货号', //表头显示的名称
      // search: true,
      dataIndex: 'orderId',
      valueType: 'select', // 列数据在数据项中对应的路径，支持通过数组查询嵌套路径
      width: 150,
      valueEnum: {
        '6PN20-1SWD02': '6PN20-1SWD02',
        '6PN20-1SWD02P': '6PN20-1SWD02P', // 会员
        '6PN201SWD02-ZB01': '6PN201SWD02-ZB01' , // 单台设备
        '6PN20-1SWD02-ZA99': '6PN20-1SWD02-ZA99', // 同类设备包年
        '6PN20-1SWD02-ZP99': '6PN20-1SWD02-ZP99', // 尊享版
      },
    },
    {
      title: '备注', //表头显示的名称
      search: false,
      dataIndex: 'memo', // 列数据在数据项中对应的路径，支持通过数组查询嵌套路径
    },

    {
      title: '购买时间', //表头显示的名称
      search: false,
      dataIndex: 'purchaseTime',
      width: 150,
    },

    {
      title: '购买时间', //表头显示的名称
      valueType: 'dateRange',
      hideInTable: true,
      dataIndex: 'purchaseTime',
    },

    {
      title: '使用时间', //表头显示的名称
      search: false,
      dataIndex: 'useTime',
      width: 150,
    },

    {
      title: '授权号数量', //表头显示的名称
      search: false,
      dataIndex: 'num', // 列数据在数据项中对应的路径，支持通过数组查询嵌套路径
      width: 110,
    },
    {
      title: '已用数量', //表头显示的名称
      search: false,
      dataIndex: 'usedNum', // 列数据在数据项中对应的路径，支持通过数组查询嵌套路径
      width: 150,
    },
    {
      title: '未使用数量', //表头显示的名称
      search: false,
      dataIndex: 'notUsedNum', // 列数据在数据项中对应的路径，支持通过数组查询嵌套路径
      width: 150,
    },
    {
      title: '所属客户', //表头显示的名称
      dataIndex: 'customerName', // 列数据在数据项中对应的路径，支持通过数组查询嵌套路径
      width: 120,

      search: false,
    },

    // access.canAdmin() ? {
    //   title: '所属客户', //表头显示的名称
    //   dataIndex: 'customerId', // 列数据在数据项中对应的路径，支持通过数组查询嵌套路径
    //   width: 120,
    //   // valueType: 'select',
    //   hideInTable: true,
    //   renderFormItem: (_, config, data) => {
    //     // 这里返回的值与Protable的render返回的值差不多,能获取到index,row,data 只是这里是获取对象组,外面会在包一层
    //     return (
    //       <DebounceSelect
    //         showSearch
    //         value={value}
    //         placeholder="Select customers"
    //         fetchOptions={fetchUserList}
    //         onChange={(newValue) => {
    //           setValue(newValue as UserValue[]);
    //           console.log(newValue, "---value---");
    //         }}
    //         style={{ width: '100%' }}
    //       />
    //     );
    //   },
    // } : {search: false},
    {
      title: '所属客户', //表头显示的名称
      dataIndex: 'customerId', // 列数据在数据项中对应的路径，支持通过数组查询嵌套路径
      width: 120,
      valueType: 'select',
      hideInTable: true,
      search: access.canAdmin() ? true : false,
      renderFormItem: (_, config, data) => {
        // 这里返回的值与Protable的render返回的值差不多,能获取到index,row,data 只是这里是获取对象组,外面会在包一层

        // 这个事v90
        return (
          <DebounceSelect
            showSearch
            placeholder="Select customers"
            fetchOptions={fetchUserList}
            // onChange={(newValue) => {
            //   setValue(newValue as UserValue[]);
            // }}
            style={{ width: '100%' }}
          />
        );
      },
    },
    {
      title: '创建人', //表头显示的名称
      search: false,
      dataIndex: 'createName',
      width: 80,
    },
    {
      title: '创建时间', //表头显示的名称
      search: false,
      dataIndex: 'createDate',
      width: 150,
      sorter: true,
    },

    {
      title: '操作',
      valueType: 'option',
      key: 'option',
      fixed: 'right',
      hideInTable: !access.canAdmin() && !access.canChiefEngineer() ? true : false,
      render: (text, record, _, action) => {
        const buttonList = [];
        if (access.canAdmin() || access.canChiefEngineer()) {
          buttonList.push(
            <a
              key="editKey"
              onClick={() => {
                // console.log(record, '----测试----');
                // 编辑用户
                formRef?.current?.setFieldsValue({
                  ...record,
                });
                setFormTitle('编辑授权号');
                setFormDisabled(true);
                setFormVisit(true);
              }}
            >
              编辑
            </a>,
          );

          buttonList.push(
            <a
              key="deleteKey"
              onClick={() => {
                Modal.confirm({
                  title: '删除License',
                  content: '确定删除License',
                  okText: '确认',
                  cancelText: '取消',
                  onOk: async () => {
                    await delLicense({ id: record.id });
                    actionRef.current.reload();
                  },
                });
                // actionRef.current.reload();
              }}
            >
              删除
            </a>,
          );
        }

        return buttonList;
      },
    },
  ];
  const formColums: FormItem[] = [
    { field: 'id', label: 'id', hidden: true },
    { field: 'identification', label: 'identification', hidden: true },
    {
      field: 'licenseType',
      label: '授权号类型',
      type: 'select',
      disabled: true,
      options: [
        { value: 1, label: 'BD推广' },
        { value: 2, label: '基础版' },
        { value: 3, label: '尊享版' },
        { value: 4, label: '高级版' },
        { value: 5, label: '10Package' },
        { value: 6, label: '50Package' },

        { value: 11, label: '会员版（年费）' },
        { value: 12, label: '单台设备' },
        { value: 13, label: '包年（同类设备）' },
        { value: 14, label: '尊享版（线下咨询）' },
      ],
    },
    {
      field: 'licenseID',
      label: '授权号',
      disabled: true,
    },
    {
      field: 'orderId',
      label: '订货号',
      disabled: true,
    },
    {
      field: 'num',
      label: '授权号数量',
      type: 'inputNumber',
      value: 200,
      disabled: true,
    },
    {
      field: 'usedNum',
      label: '已用数量',
      type: 'inputNumber',
      value: 0,
      disabled: true,
    },
    {
      field: 'notUsedNum',
      label: '未用数量',
      type: 'inputNumber',
      value: 200,
      disabled: true,
    },

    {
      field: 'original',
      label: '授权号来源',
      value: 1,
      type: 'select',

      options: [
        { value: 1, label: 'GMC' },
        { value: 2, label: '转让' },
      ],
    },

    {
      field: 'originalName',
      label: '来源名称',
      value: '0000',
    },
    {
      field: 'nextGoing',
      label: '授权号去向',
      type: 'select',

      options: [
        { value: 1, label: 'GMC' },
        { value: 2, label: '转让' },
      ],
    },
    {
      field: 'memo',
      label: '备注',
    },
  ];

  const handleSubmit = async () => {
    if (formTitle == '新建授权号') {
      await addLicense(formRef.current.getFieldsValue());
    } else {
      await updateLicense(formRef.current.getFieldsValue());
    }
    setFormVisit(false);
    actionRef.current.reload();
    message.success('添加成功');
    // setModalVisit(false);
    // 这个爆红不用管(从新加载页面)
  };

  const handleSubmit2 = async () => {
    console.log(selectRows, '---selectRows---');
    setConfirmLoading(true);
    if (selectRows.length <= 0) {
      return message.error('请先选择数据');
    }
    if (formUserTitle == '授权') {
      console.log(form.getFieldValue('customerId'), '---customerId---');
      await updateLicensesUser({
        customerId: form.getFieldValue('customerId').value,
        licenseIds: selectRows,
      });
    } else {
      if (
        form.getFieldValue('customerId') == null ||
        form.getFieldValue('customerId') == undefined
      ) {
        setConfirmLoading(false);
        return message.error('客户信息不能为空');
      }
      await updateLicensesCustomer({
        customerId: form.getFieldValue('customerId').value,
        licenseIds: selectRows,
        notUsedNums: form.getFieldValue('transNums'),
      });
    }

    setConfirmLoading(false);
    setFormUserVisit(false);
    message.success('添加成功');

    actionRef.current.reload();
    actionRef.current.clearSelected();
    // setModalVisit(false);
  };
  return (
    <div>
      <PageContainer title={false} breadcrumb={undefined}>
        <ProTable //表格Pro组件
          headerTitle="授权号查询" //表头
          actionRef={actionRef} //用于触发刷新操作等，看api
          formRef={ref}
          rowKey="id" //表格行 key 的取值，可以是字符串或一个函数
          toolBarRender={(action, { selectedRows, selectedRowKeys }) => {
            if (access.canAdmin()) {
              return [
                <Button
                  key="gen"
                  icon={<PlusOutlined />}
                  onClick={() => {
                    // console.log(selectedRows, '---选取多行----');
                    // 1.清空form
                    genFormRef?.current?.resetFields();
                    setGenVisible(true);

                    //
                  }}
                  type="primary"
                >
                  生成
                </Button>,

                <Button
                  key="button"
                  icon={<PlusOutlined />}
                  onClick={() => {
                    // console.log(selectedRows, '---选取多行----');
                    // 1.清空form
                    setUploadVisit(true);
                  }}
                  type="primary"
                >
                  导入
                </Button>,
                <Button
                  key="button"
                  icon={<PlusOutlined />}
                  onClick={() => {
                    // console.log(selectedRows, '---选取多行----');
                    // 1.清空form
                    console.log(ref.current.getFieldsValue(), '----ref--');

                    licenseExcelExport({
                      current: 1,
                      pageSize: 5000,
                      ...ref.current.getFieldsValue(),
                    }).then((res) => {
                      const aLink = document.createElement('a');
                      document.body.appendChild(aLink);
                      aLink.style.display = 'none';
                      aLink.href = window.URL.createObjectURL(res);
                      aLink.setAttribute('download', `授权号${new Date()}.xlsx`);
                      aLink.click();
                      document.body.removeChild(aLink);
                    });
                  }}
                  type="primary"
                >
                  导出
                </Button>,

                <Button
                  key="button"
                  icon={<PlusOutlined />}
                  onClick={() => {
                    // console.log(selectedRows, '---选取多行----');
                    // 1.清空form
                    if (selectedRowKeys == undefined || selectedRowKeys?.length <= 0) {
                      message.error('请先选择数据');
                    } else if (selectedRows.map((item) => item.customerId).includes(null)) {
                      message.error('有空客户请先赋值');
                    } else {
                      const list = selectedRows
                        .filter((item) => item.customerId !== null)
                        .map((item) => item.customerId);
                      const list2 = [...new Set(list)];
                      console.log(list2, '---list2---');
                      if (list2.length <= 0 || list2.length >= 2) {
                        message.error('license所属客户不正确请从新选择');
                      } else {
                        setCustomerId(list2[0]); //获取id
                        const customerName = selectedRows
                          .filter((item) => item.customerId == list2[0])
                          .map((item) => {
                            return { customerName: item.customerName, customerId: customerName };
                          });
                        setEmailinitialValues({
                          customerName: customerName[0].customerName,
                          customerId: customerName[0].customerId,
                        });
                        setSelectRows(selectedRowKeys); //获取选择Id
                        setCustomerName(customerName[0].customerName);
                        setMailVisible(true);
                      }
                    }

                    // licenseWordDownLoad().then((res) => {
                    //   const aLink = document.createElement('a');
                    //   document.body.appendChild(aLink);
                    //   aLink.style.display = 'none';
                    //   aLink.href = window.URL.createObjectURL(res);
                    //   aLink.setAttribute('download', `授权号${new Date()}.zip`);
                    //   aLink.click();
                    //   document.body.removeChild(aLink);
                    // });
                  }}
                  type="primary"
                >
                  邮件发送
                </Button>,

                <Button
                  key="button"
                  icon={<PlusOutlined />}
                  onClick={() => {
                    console.log(selectedRows, '---多行数据----');

                    // 1.清空form
                    if (selectedRowKeys == undefined || selectedRowKeys?.length <= 0) {
                      message.error('请先选择数据');
                    } else {
                      if (selectedRows.map((item) => item.status).includes(true)) {
                        message.error('有包含已经使用的授权号请重新选择');
                      } else {
                        setSelectRows(selectedRowKeys);
                        setFormUserVisit(true);
                        setFormUserTitle('授权');
                      }
                    }
                  }}
                  type="primary"
                >
                  授权
                </Button>,

                <Button
                  key="button"
                  icon={<PlusOutlined />}
                  onClick={() => {
                    Modal.confirm({
                      title: '删除License',
                      content: '确定删除License',
                      okText: '确认',
                      cancelText: '取消',
                      onOk: async () => {
                        await delLicenses(selectedRowKeys);
                        actionRef.current.reload();
                      },
                    });

                    // 1.清空form
                  }}
                  type="primary"
                >
                  删除
                </Button>,
              ];
            } else {
              return [
                <Button
                  key="button"
                  icon={<PlusOutlined />}
                  onClick={() => {
                    // console.log(selectedRows, '---选取多行----');
                    // 1.清空form
                    console.log(ref.current.getFieldsValue(), '----ref--');
                    licenseExcelExport({
                      current: 1,
                      pageSize: 5000,
                      ...ref.current.getFieldsValue(),
                    }).then((res) => {
                      const aLink = document.createElement('a');
                      document.body.appendChild(aLink);
                      aLink.style.display = 'none';
                      aLink.href = window.URL.createObjectURL(res);
                      aLink.setAttribute('download', `授权号${new Date()}.xlsx`);
                      aLink.click();
                      document.body.removeChild(aLink);
                    });
                  }}
                  type="primary"
                >
                  导出
                </Button>,
                <Button
                  key="button"
                  icon={<PlusOutlined />}
                  hidden={access.canCustomer()}
                  onClick={() => {
                    console.log(selectedRows, '---选取多行----');
                    // 1.清空form

                    // 1.清空form
                    if (selectedRowKeys == undefined || selectedRowKeys?.length <= 0) {
                      message.error('请先选择数据');
                    } else {
                      console.log(selectedRowKeys, '---选取多行----');
                      // 1.清空form
                      const notUsedNums = selectedRows
                        .map((item) => item.notUsedNum)
                        .reduce((item, item2) => item + item2);

                      console.log(notUsedNums, '---选取多行----');
                      setFormUserTitle('转让');
                      setSelectRows(selectedRowKeys);
                      setFormUserVisit(true);
                      setTransNumMax(notUsedNums);
                      form.setFieldsValue({
                        // transNums: notUsedNums,
                        // type:record.type,
                        // sysPresetFlag:record.sysPresetFlag,
                      });
                    }
                  }}
                  type="primary"
                >
                  转让
                </Button>,
              ];
            }
          }}
          revalidateOnFocus={false}
          request={async (params = {}, sort, filter) => {
            let result;
            // let customerId =
            //   params.customerId !== null
            //     ? params.customerId
            //     : location.query.customerId !== null
            //     ? location.query.customerId
            //     : null;
            console.log(params.customerId, location.query.customerId, 'ceshi----ceshi1');
            let customerValue =
              params.customerId !== undefined 
                ? params?.customerId?.value
                : location.query.customerId !== undefined
                ? location.query.customerId
                : null;
            delete params.customerId;
            // if (location.query.customerId === undefined || location.query.customerId === null) {
            result = await getLicenseByPage({ ...params, customerId: customerValue });
            // } else {
            //   result = await getLicenseByPage({
            //     ...params,
            //     // orderId: location.query.orderId,
            //     customerId: location.query.customerId,
            //   });
            // }
            return {
              data: result.data.content,
              total: result.data.totalElements,
              success: result.success,
            };
            // return  await new Promise({data:[{loginName:}], total:10, success: 0})
            // return {data:[], total:10, success: 0}
          }} //请求数据的地方，例子是用mock模拟数据，我是在后台请求的数据
          columns={columns} //上面定义的
          onDataSourceChange={(value) => {
            // 如果实在要保存新的值就需要在这边进行处理
            // console.log(value, selectedRowKeys, '---teee');
          }}
          rowSelection={rowSelection}
          pagination={{
            showSizeChanger: true,
          }}
          scroll={{ x: 2070, y: 350 }}
        />
        <ModalForm
          title={formUserTitle}
          visible={formUserVisit}
          onFinish={handleSubmit2}
          form={form}
          modalProps={{
            destroyOnClose: true,
            onCancel: () => {
              setFormUserVisit(false);
            },
          }}
          layout={formLayoutType}
          grid={grid}
          rowProps={{
            gutter: [12, formLayoutType === 'inline' ? 12 : 0],
          }}
          width={500}
        >
          <ProFormGroup>
            <Form.Item label="客户信息" name="customerId" colProps={{ md: 16, xl: 12 }}>
              {access.canAdmin() ? (
                <DebounceSelect
                  showSearch
                  value={value}
                  placeholder="Select customers"
                  fetchOptions={fetchUserList}
                  onChange={(newValue) => {
                    setValue(newValue as UserValue[]);
                  }}
                  style={{ width: '300px' }}
                />
              ) : (
                <DebounceSelect
                  showSearch
                  value={value}
                  placeholder="Select customers"
                  fetchOptions={fetchUserCodeList}
                  onChange={(newValue) => {
                    setValue(newValue as UserValue[]);
                  }}
                  style={{ width: '300px' }}
                />
              )}
            </Form.Item>
            {/* <ProFormSelect
              fieldProps={{
                filterOption: () => {
                  return true;
                },
              }}
              width="md"
              name="customerId"
              label="客户信息"
              colProps={{ md: 24, xl: 20 }}
              debounceTime={1000}
              showSearch
              // options={async (params) => {
              //   const result = access.canAdmin()
              //     ? await customerList({ blurry: params.keyWords })
              //     : await customerCodeList({ blurry: params.keyWords });
              //   console.log('param---- ', param);
              //   return result.data.map((item) => {
              //     return {
              //       label: item.name,
              //       value: item.id,
              //       search: item.code,
              //     };
              //   });
              // }}
              request={async (params) => {
                const result = access.canAdmin()
                  ? await customerList({ blurry: params.keyWords })
                  : await customerCodeList({ blurry: params.keyWords });
                console.log(params.keyWords, '---customer result---');
                return result.data.map((item) => {
                  return {
                    label: item.name,
                    value: item.id,
                    // search: item.code,
                  };
                });
              }}
            /> */}
          </ProFormGroup>
          <ProFormGroup>
            <ProFormDigit
              width="md"
              colProps={{ md: 16, xl: 12 }}
              name="transNums"
              key="transNums"
              label="转移数量"
              initialValue={0}
              hidden={access.canAdmin()}
              min={0}
              max={transNumMax}
              extra={'数量范围需在0~' + transNumMax + '之间'}
              // rules={[{ max: transNumMax }]}
            />
          </ProFormGroup>
        </ModalForm>

        <ToeForm
          visible={formVisit}
          title="新建授权号"
          disabled={formDisabled}
          ref={formRef}
          initialValues={{
            num: 200,
            usedNum: 0,
            notUsedNum: 200,
            original: 1,
            originalName: '0000',
          }}
          columns={formColums}
          onCancel={() => {
            setFormVisit(false);
          }}
          onOk={handleSubmit}
        />
        <ToeUpload
          onCancel={() => {
            setUploadVisit(false);
          }}
          ref={uploadRef}
          onOk={async () => {
            const formData = new FormData();
            console.log(uploadRef.current.fileList, '文件测试---');
            uploadRef.current.fileList.map((file) => {
              formData.append('file', file);
            });
            // formData.append('file', 'jja');
            console.log(formData, '---formData--');
            await uploadLicenseExcel(formData);
            actionRef.current.reload();
            setUploadVisit(false);
          }}
          visible={uploadVisit}
          title="文件上传"
        />

        <ModalForm
          title="生成授权号"
          visible={genVisible}
          formRef={genFormRef}
          onFinish={async (values) => {
            await genLicense(values);
            setGenVisible(false);
            actionRef.current.reload();

            return true;
          }}
          onValuesChange={(changeValues) => {
            // 判断不为空
            if (changeValues.licenseType !== null && changeValues.licenseType !== undefined) {
              genFormRef.current?.setFieldsValue({
                unitPrice: null,
                num: null,
                totalPrice: null,
                purchaseType: null,
              });
            }

            // const pTime = genFormRef.current?.getFieldValue('purchaseTime');
            // let dueDate = dayjs(pTime).add(+3, 'y').format('YYYY-MM-DD');
            // genFormRef.current?.setFieldsValue({ expiryTime: dueDate });

            if (changeValues.purchaseTime !== null && changeValues.purchaseTime !== undefined) {
              const pTime = genFormRef.current?.getFieldValue('purchaseTime');
              let dueDate = dayjs(pTime).add(+1, 'y').format('YYYY-MM-DD');
              console.log('---expiryTime: dueDate---', dueDate);
              genFormRef.current?.setFieldsValue({ expiryTime: dueDate });
            }

            if (changeValues.purchaseType !== null && changeValues.purchaseType !== undefined) {
              if (changeValues.purchaseType === 1) {
                genFormRef.current?.setFieldsValue({ unitPrice: 150, num: 1, totalPrice: 150 });
              } else if (changeValues.purchaseType === 2) {
                genFormRef.current?.setFieldsValue({ unitPrice: 100, num: 100, totalPrice: 10000 });
              } else if (changeValues.purchaseType === 3) {
                genFormRef.current?.setFieldsValue({ unitPrice: 80, num: 500, totalPrice: 40000 });
              } else if (changeValues.purchaseType === 11) {
                genFormRef.current?.setFieldsValue({ unitPrice: 1500, num: 1, totalPrice: 1500 });
              } else if (changeValues.purchaseType === 12) {
                genFormRef.current?.setFieldsValue({ unitPrice: 750, num: 40, totalPrice: 30000 });
              } else if (changeValues.purchaseType === 13) {
                genFormRef.current?.setFieldsValue({ unitPrice: 600, num: 100, totalPrice: 60000 });
              }
            }

            if (changeValues.licenseType !== null && changeValues.licenseType !== undefined) {
              if (changeValues.licenseType === 11) {
                // 会员版（年费）
                genFormRef.current?.setFieldsValue({ unitPrice: 365, num: 1, totalPrice: 365, orderId: '6PN20-1SWD02' });
              } else if (changeValues.licenseType === 12) {
                // 单台设备
                genFormRef.current?.setFieldsValue({ unitPrice: 1500, num: 1, totalPrice: 1500, orderId: '6PN201SWD02-ZB01' });
              } else if (changeValues.licenseType === 13) {
                // 包年（同类设备）
                genFormRef.current?.setFieldsValue({ unitPrice: 50000, num: 1, totalPrice: 50000, orderId: '6PN20-1SWD02-ZA99' });
              } else if (changeValues.licenseType === 14) {
                // 尊享版（线下咨询）
                genFormRef.current?.setFieldsValue({ unitPrice: 100000, num: 1, totalPrice: 100000, orderId: '6PN20-1SWD02-ZP99' });
              } 
            }

            // 数量不变，总价变
            if (changeValues.num !== null && changeValues.num !== undefined) {
              const result = genFormRef.current?.getFieldValue('totalPrice');
              let temp = result / changeValues.num;
              genFormRef.current?.setFieldsValue({ unitPrice: temp.toFixed(3) });
            }

            // 总价不变，数量变
            if (changeValues.totalPrice !== null && changeValues.totalPrice !== undefined) {
              const result = genFormRef.current?.getFieldValue('num');
              let temp = changeValues.totalPrice / result;
              genFormRef.current?.setFieldsValue({ unitPrice: temp.toFixed(3) });
            }
          }}
          layout={formLayoutType}
          grid={grid}
          rowProps={{
            gutter: [16, formLayoutType === 'inline' ? 16 : 0],
          }}
          modalProps={{
            destroyOnClose: false,
            onCancel: () => {
              setGenVisible(false);
            },
          }}
          // submitter={{
          //   searchConfig: {
          //     resetText: '重置',
          //   },
          //   resetButtonProps: {
          //     onClick: () => {
          //       formRef.current?.setFieldsValue({ shaftName: '测试', hardwareIdentifier: 'hhh' });
          //       // formRef.current?.resetFields();
          //       //   setModalVisible(false);
          //     },
          //   },
          // }}
          // onOpenChange={() => {

          // }}
          // onOpenChange={setVisible}
        >
          <ProFormGroup title="通用配置项目">
            <ProFormSelect
              width="md"
              name="orderId"
              label="订货号"
              rules={[{ required: true, message: '必须填写订货号' }]}
              colProps={{ md: 12, xl: 8 }}
              options={[
                { label: '6PN20-1SWD02P', value: '6PN20-1SWD02P' },
                { label: '6PN20-1SWD02', value: '6PN20-1SWD02' }, // 会员
                { label: '6PN201SWD02-ZB01', value: '6PN201SWD02-ZB01' }, // 单台设备
                { label: '6PN20-1SWD02-ZA99', value: '6PN20-1SWD02-ZA99' }, // 同类设备包年
                { label: '6PN20-1SWD02-ZP99', value: '6PN20-1SWD02-ZP99' }, // 尊享版
              ]}
            />
            <ProFormSelect
              width="md"
              name="original"
              label="授权号来源"
              colProps={{ md: 12, xl: 8 }}
              rules={[{ required: true, message: '必须填写授权号来源' }]}
              options={[
                { label: 'GMC', value: 1 },
                { label: '转让', value: 2 },
              ]}
            />
            <ProFormText
              width="md"
              name="originalName"
              label="来源名称"
              colProps={{ md: 12, xl: 8 }}
              initialValue="GMC"
              // rules={[{ required: true, message: '来源名称' }]}
            />

            <ProFormText
              name="purchasePhone"
              label="购买电话"
              colProps={{ md: 12, xl: 8 }}
              rules={[{ required: true, message: '必须填写订货电话' }]}
            />
            
            <ProFormDatePicker
              name="purchaseTime"
              key="purchaseTime"
              label="购买日期"
              colProps={{ md: 12, xl: 8 }}
              rules={[{ required: true, message: '必须填写购买日期' }]}
            />
            <ProFormDatePicker
              name="expiryTime"
              key="expiryTime"
              label="结束日期"
              colProps={{ md: 12, xl: 8 }}
              rules={[{ required: true, message: '必须填写结束日期' }]}
            />
            

            <ProFormSelect
              width="md"
              name="licenseType"
              label="授权号类型"
              colProps={{ md: 12, xl: 12 }}
              rules={[{ required: true, message: '必须填写授权号类型' }]}
              options={[
                { label: '会员版（年费）', value: 11 },
                { label: '单台设备', value: 12 },
                { label: '包年（同类设备）', value: 13 },
                { label: '尊享版（线下咨询）', value: 14 },

                { label: '基本版', value: 2 },
                { label: '堆垛机版', value: 7 },
              ]}
            />

            <ProFormText
              width="md"
              name="memo"
              label="备注"
              colProps={{ md: 12, xl: 12 }}
              // rules={[{ required: true, message: '备注' }]}
            />
          </ProFormGroup>

          


          <ProFormDependency name={['licenseType']}>
            {({ licenseType }) => {
              if (licenseType == 2 || licenseType == 7) {
                return (
                  <ProFormGroup title="购买版本">
                    <ProFormDependency name={['licenseType']}>
                      {({ licenseType }) => {
                        if (licenseType == 2) {
                          return (
                            <ProFormSelect
                              showSearch
                              width="md"
                              name="purchaseType"
                              label="基本版本购买类型"
                              rules={[{ required: true, message: '必须填写订货号' }]}
                              options={[
                                { label: '基本版 S', value: 1 },
                                { label: '基本版 P_100轴', value: 2 },
                                { label: '基本版 P_500轴', value: 3 },
                              ]}
                            />
                          );
                        } else if (licenseType == 7) {
                          return (
                            <ProFormSelect
                              showSearch
                              width="md"
                              name="purchaseType"
                              label="堆垛机版"
                              rules={[{ required: true, message: '必须填写订货号' }]}
                              options={[
                                { label: '堆垛机版 S', value: 11 },
                                { label: '堆垛机版 P_40台', value: 12 },
                                { label: '堆垛机版 P_100台', value: 13 },
                              ]}
                            />
                          );
                        }
                      }}
                    </ProFormDependency>
                  </ProFormGroup>
      
                );
              }
            }}
          </ProFormDependency>



          <ProFormGroup title="选购类型">
            <ProFormMoney
              label="单价"
              key="unitPrice"
              name="unitPrice"
              disabled
              locale="en-ZH"
              colProps={{ md: 12, xl: 8 }}
            />
            <ProFormDigit key="num" name="num" colProps={{ md: 12, xl: 8 }} label="数量" />
            <ProFormMoney
              key="totalPrice"
              name="totalPrice"
              locale="en-ZH"
              colProps={{ md: 12, xl: 8 }}
              label="总价"
            />
          </ProFormGroup>
        </ModalForm>

        <ModalForm
          title="发送邮件填写"
          visible={mailVisible}
          formRef={mailFormRef}
          onFinish={async (values) => {
            console.log(values, '----selectRows---');
            await sendEmail({ ...values, licenseIds: selectRows });
            setMailVisible(false);
            actionRef.current.reload();

            return true;
          }}
          initialValues={emailinitialValues}
          layout={formLayoutType}
          grid={grid}
          rowProps={{
            gutter: [16, formLayoutType === 'inline' ? 16 : 0],
          }}
          modalProps={{
            destroyOnClose: true,
            onCancel: () => {
              setMailVisible(false);
            },
          }}
        >
          <ProFormGroup title="邮件详情">
            <ProFormText
              width="md"
              name="customerId"
              label="客户Id"
              hidden={true}
              colProps={{ md: 12, xl: 8 }}
              disabled
            />
            <ProFormText
              width="md"
              name="customerName"
              label="客户名称"
              colProps={{ md: 12, xl: 12 }}
              disabled
            />
            <ProFormSelect
              showSearch
              width="md"
              name="userId"
              label="所选用户"
              rules={[{ required: true, message: '必须选取用户' }]}
              colProps={{ md: 12, xl: 12 }}
              debounceTime={1000}
              request={async (params) => {
                console.log(params, '--params-');
                const result = await userLicenseList({
                  blurry: params.keyWords,
                  customerId: customerId,
                });

                return result.data.map((item) => {
                  return {
                    key: item.id,
                    label: item.name,
                    value: item.id,
                  };
                });
              }}
            />
            <ProFormText
              width="md"
              name="customerOrderNo"
              label="商城订单号"
              rules={[{ required: true, message: '商城订单号不能为空' }]}
              colProps={{ md: 12, xl: 24 }}
            />
          </ProFormGroup>
        </ModalForm>
      </PageContainer>
    </div>
  );
};

export default LicenseAdm;
